<script setup lang="ts">
import { createConsultOrder, getConsultOrderPayUrl, getConsultOrderPre } from '@/services/consult'
import { onMounted } from 'vue'
import { useConsultStore } from '@/stores'
import { ref } from 'vue'
import type { ConsultOrderPreData } from '@/types/consult'
import { getPatientDetail } from '@/services/user'
import type { Patient } from '@/types/user'
import { showConfirmDialog, showDialog, showLoadingToast, showToast } from 'vant'
import { useRouter } from 'vue-router'
import { onBeforeRouteLeave } from 'vue-router'
import type CpPaySheetVue from '@/components/CpPaySheet.vue'
const consultStore = useConsultStore()
const agree = ref(false)
// 获取预支付信息
const payInfo = ref({} as ConsultOrderPreData)
const getPayInfo = async () => {
  const res = await getConsultOrderPre({
    type: consultStore.consult.type,
    illnessType: consultStore.consult.illnessType
  })
  payInfo.value = res.data
  // 存储优惠券信息
  consultStore.setCoupon(res.data.couponId)
}

// 获取患者信息
const patient = ref({} as Patient)
const getPatient = async () => {
  const res = await getPatientDetail(consultStore.consult.patientId as string)
  patient.value = res.data
}
onMounted(() => {
  // 加载页面时 发现问诊记录没有了 提示用户 并跳转首页
  if (
    !consultStore.consult.type ||
    !consultStore.consult.illnessType ||
    !consultStore.consult.depId ||
    !consultStore.consult.patientId
  ) {
    return showDialog({
      title: '温馨提示',
      message: '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付'
    }).then(() => {
      // 跳转到首页
      router.push('/')
    })
  }
  getPayInfo()
  getPatient()
})

// 生成订单
// 抽屉
const show = ref(false)

//  Loading
const loading = ref(false)
// 订单ID
const orderId = ref('')
const createOrder = async () => {
  if (!agree.value) return showToast('请勾选我已同意')
  // 打开loading
  loading.value = true
  try {
    const res = await createConsultOrder(consultStore.consult)
    orderId.value = res.data.id
    // 清空问诊记录所有的数据
    consultStore.clear()
    // 打开选择支付方式的弹窗
    show.value = true
  } finally {
    // 关闭loading
    loading.value = false
  }
}

// 用户关闭抽屉之前
const router = useRouter()
const beforeClose = async () => {
  try {
    await showConfirmDialog({
      title: '关闭支付',
      message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
      cancelButtonText: '仍要关闭',
      confirmButtonText: '继续支付'
    })
    // 点击继续支付，阻止抽屉关闭
    return false
  } catch (error) {
    // 跳转页面前，清空订单ID
    orderId.value = ''
    // 点击仍要关闭，跳转到问诊订单页
    router.push('/user/consult')
    // 关闭抽屉
    return true
  }
}
// 如果已经有订单了 点返回不可返回
onBeforeRouteLeave(() => {
  if (orderId.value) return false
})
</script>

<template>
  <div class="consult-pay-page">
    <cp-nav-bar title="支付" />
    <!-- 预支付信息 -->
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <!-- 患者信息 -->
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patient.name} | ${patient.genderValue} | ${patient.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="consultStore.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <!-- 底部操作栏 -->
    <van-submit-bar
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="createOrder"
      :loading="loading"
    />
  </div>
  <!-- 支付抽屉组件 -->
  <cp-pay-sheet
    v-model:show="show"
    :orderId="orderId"
    :actualPayment="payInfo.actualPayment"
    :beforeClose="beforeClose"
    payCallback="/room"
  ></cp-pay-sheet>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
</style>
